package com.rasou.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public abstract class AbstractConfigSource implements ConfigSource {

    private final String name;

    private final int ordinal;

    private Map<String, String> configData;

    protected AbstractConfigSource(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
        this.configData = new HashMap<>();
    }


    @Override
    public final Map<String, String> getProperties() {
        return Collections.unmodifiableMap(getConfigData());
    }

    protected Map<String, String> getConfigData() {
        try {
            if (configData.isEmpty()) {
                return addConfig(configData);
            }
        } catch (Throwable cause) {
            throw new IllegalStateException("准备配置数据发生错误", cause);
        }
        return configData;
    }

    @Override
    public Set<String> getPropertyNames() {
        return this.configData.keySet();
    }

    @Override
    public int getOrdinal() {
        return this.ordinal;
    }

    @Override
    public String getValue(String propertyName) {
        return configData.computeIfPresent(propertyName, (k, v) -> v);
    }

    @Override
    public String getName() {
        return this.name;
    }

    protected abstract Map addConfig(Map data);
}
